package com.myblog.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.myblog.common.ResultInfoFactory;
import com.myblog.model.po.Tags;
import com.myblog.service.TagsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author
 * @since 2022-09-04
 */
@Controller
@RequestMapping("/tag")
public class TagsController {

    private static final String HTML_PREFIX="admin/tag/";

    @Autowired
    private TagsService tagsService;

    @GetMapping(value = {"/",""})
    public String tag(){
        return HTML_PREFIX+"tag-list";
    }

    @PreAuthorize("hasAuthority('sys:tag:list')")
    @ResponseBody
    @PostMapping("/page")
    public ResultInfoFactory page(Page<Tags> page, Tags tags){
        IPage<Tags> sysRoleIPage = tagsService.selectPage(page, tags);
        return ResultInfoFactory.success(sysRoleIPage);
    }


    @PreAuthorize("hasAnyAuthority('sys:tag:add','sys:tag:edit')")
    @GetMapping(value = {"/form","/form/{id}"})
    public String form(@PathVariable(required = false)Long id, Model model){
        if(id==null){
            model.addAttribute("tag",new Tags());
        }else {
            Tags tag = tagsService.getById(id);
            model.addAttribute("tag",tag);
        }
        return HTML_PREFIX+"tag-form";
    }
    @PreAuthorize("hasAnyAuthority('sys:tag:add','sys:tag:edit')")
    @RequestMapping(value = {"/saveOrUpdate"},method = {RequestMethod.POST,RequestMethod.PUT})
    public String saveOrUpdate(Tags tags){
        //log.info(sysRole.toString());
        tagsService.saveOrUpdate(tags);
        return "redirect:/tag";
    }

    @PreAuthorize("hasAuthority('sys:tag:delete')")
    @DeleteMapping("/{id}")
    @ResponseBody
    public ResultInfoFactory deleteById(@PathVariable("id") Long id){
        tagsService.removeById(id);
        return ResultInfoFactory.success();
    }


}
